#include "config.h"
#include <QDebug>
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QDebug>
std::unique_ptr <configmanager> configmanager::m_InStance = nullptr;
std::once_flag configmanager::m_Flag;

configmanager& configmanager::GetInstance()
{
    std::call_once(m_Flag,[](){
       m_InStance.reset(new configmanager());
    });
    return *m_InStance;
}
configmanager::configmanager() {

}

configmanager::~configmanager() {

}

//CRC 校验
Config configmanager::readAndParseJson(const QString &filePath){
    Config config;
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << "Failed to open file:" << filePath;
        return config;
    }

    QByteArray data = file.readAll();
    file.close();

    QJsonDocument jsonDoc = QJsonDocument::fromJson(data);
    if (jsonDoc.isNull()) {
        qWarning() << "Failed to parse JSON";
        return config;
    }

    QJsonObject jsonObj = jsonDoc.object();
    // 填充 Config 结构体字段
    config.Dir = jsonObj["Dir"].toString();
    config.FtpConf = jsonObj["FtpConf"].toString();
    config.ExpireDate = jsonObj["ExpireDate"].toString();
    config.UsageThreshold = jsonObj["UsageThreshold"].toDouble();
    config.hostAddress = jsonObj["hostAddress"].toString();

    QJsonObject dataBaseObj = jsonObj["DataBase"].toObject();
    config.DataBase.username = dataBaseObj["username"].toString();
    config.DataBase.password = dataBaseObj["password"].toString();
    config.DataBase.hostDB = dataBaseObj["hostDB"].toString();
    config.DataBase.dbname = dataBaseObj["dbname"].toString();
    config.DataBase.patroltal = dataBaseObj["patroltal"].toString();
    config.DataBase.postionbl = dataBaseObj["postionbl"].toString();
    config.DataBase.dbpath = dataBaseObj["dbpath"].toString();
    return config;
}
